package com.ruoyi.system.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.ruoyi.common.core.domain.entity.AccessTokenData;
import com.ruoyi.system.service.ISystemConfigService;
import com.ruoyi.system.service.InvoiceService;
import com.ruoyi.system.third.constant.InvoiceConstant;
import com.ruoyi.system.third.constant.InvoiceParkingConfigConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 发票服务接口实现类
 */
@Service
public class InvoiceServiceImpl implements InvoiceService {

    @Autowired
    private ISystemConfigService systemConfigService;



    // Gson实例，用于JSON处理
    private static final Gson gson =  new GsonBuilder()
            .disableHtmlEscaping()
            .create();


    /**
     * 开票方法
     * @return 操作结果
     */
    @Override
    public Map<String, Object> fpkj(Map<String, Object> info) {

        // 从配置服务获取电子发票AppID
        String appId = systemConfigService.getValue(InvoiceParkingConfigConstants.INVOICE_APPID);
        // 从配置服务获取电子发票AppSecret
        String appSecret = systemConfigService.getValue(InvoiceParkingConfigConstants.INVOICE_APPSECRET);


        // 接口路径
        String interfaceUrl = "invoiceEx/zpy/electric/invoice/issued";

        // 构建开票信息
        Map<String, Object> kpInfo = new HashMap<>();
        // 备注
        kpInfo.put("bz", info.get("bz"));
        // 1 自助开票
        kpInfo.put("yhlx", "1");
        // 发票类型代码，82为数电普票
        kpInfo.put("fplxdm", "82");
        // 发票请求流水号
        kpInfo.put("fpqqlsh", info.get("order_sn"));
        // 含税标志：1-含税
        kpInfo.put("hsbz", "1");
        // 购方信息校验
        kpInfo.put("gfxxqr", "");

        // 构建明细列表
        Map<String, Object> mxList = new HashMap<>();
        // 单价
        mxList.put("dj", info.get("TotalAmount"));
        // 单位
        mxList.put("dw", systemConfigService.getValue(InvoiceParkingConfigConstants.UNIT));
        // 发票行性质
        mxList.put("fphxz", "0");
        // 金额
        mxList.put("je", info.get("TotalAmount"));
        // 税率标示
        mxList.put("lslbs", systemConfigService.getValue(InvoiceParkingConfigConstants.TAX_RATE_FLAG));
        // 税额
        mxList.put("se", se(mxList.get("je")));

        // 税率（从配置获取）
        String taxRate = systemConfigService.getValue(InvoiceParkingConfigConstants.TAX_RATE);
        mxList.put("sl", taxRate);

        // 税收分类编码
        mxList.put("spbm", systemConfigService.getValue(InvoiceParkingConfigConstants.TAX_CLASSIFICATION_CODE));
        // 商品名称
        mxList.put("spmc", systemConfigService.getValue(InvoiceParkingConfigConstants.GOODS_NAME));
        // 商品数量
        mxList.put("spsl", systemConfigService.getValue(InvoiceParkingConfigConstants.GOODS_QUANTITY));
        // 优惠政策标识
        mxList.put("yhzcbs",systemConfigService.getValue(InvoiceParkingConfigConstants.PREFERENTIAL_POLICY_FLAG));
        // 增值税特殊管理标识
        mxList.put("zzstsgl", systemConfigService.getValue(InvoiceParkingConfigConstants.VAT_SPECIAL_MANAGEMENT_FLAG));
        // 明细集合
        kpInfo.put("mxList", new Object[]{mxList});
        // 纳税人识别
        kpInfo.put("nsrsbh", systemConfigService.getValue(InvoiceParkingConfigConstants.TAXPAYER_IDENTIFICATION_NUMBER));

        // 构建附加信息
        Map<String, Object> spExt = new HashMap<>();
        // 回调通知地址--开票成功的话，会
        spExt.put("hddz", "https://dyc.mallmember.cn/system/invoice/index");
        // 电话号码
        spExt.put("sjhm", "");
        // 邮箱
        spExt.put("yxdz", "");
        kpInfo.put("spExt", spExt);
        // 特定要素类型代码
        kpInfo.put("tdyslxdm", "06");

        // 构建特定要素信息
        Map<String, Object> bdcjyzlfw = new HashMap<>();
        bdcjyzlfw.put("fwcqzshm", "无");
//        不动产地址，不动产经营租赁服务必填
        bdcjyzlfw.put("bdcdz", systemConfigService.getValue(InvoiceParkingConfigConstants.REAL_ESTATE_ADDRESS));
//        跨地市标志，0：否  1：是
        bdcjyzlfw.put("kdsbz", 0);
//        租赁期起，格式:yyyyMMdd，若商品编码为3040502020200000000时，可传yyyyMMddHHmm
        bdcjyzlfw.put("zlqq", systemConfigService.getValue(InvoiceParkingConfigConstants.LEASE_START_DATE));
//        租赁期止，格式:yyyyMMdd，可传yyyyMMddHHmm
        bdcjyzlfw.put("zlqz", systemConfigService.getValue(InvoiceParkingConfigConstants.LEASE_END_DATE));

//面积单位，米（铁路线与管道等使用）,平方千米,平方米,孔公里,公顷,亩, hm², km², m²。
//该字段值会作为实际发票商品行的单位，红字申请时，需填写该字段的赋值

        bdcjyzlfw.put("mjdw", systemConfigService.getValue(InvoiceParkingConfigConstants.AREA_UNIT));
        kpInfo.put("bdcjyzlfw", bdcjyzlfw);

        kpInfo.put("xfdz", "");
        kpInfo.put("xfkhh", "");
        kpInfo.put("xflxdh", "");
//        销方名称
        kpInfo.put("xfmc", systemConfigService.getValue(InvoiceParkingConfigConstants.SELLER_NAME));
        kpInfo.put("xfyhzh", "");
        kpInfo.put("skr", "");
        kpInfo.put("fhr", "");
        kpInfo.put("zsgfyh", "");
        kpInfo.put("zsxfyh", "");

        // 将开票信息转换为JSON字符串
        String conten = gson.toJson(kpInfo);

        // 构建请求参数
        Map<String, Object> parasMap = new HashMap<>();
        parasMap.put("serviceId", "FPKJ");
        parasMap.put("dlzh", InvoiceConstant.DLZH);
        parasMap.put("nsrsbh", InvoiceConstant.NSRSBH);
        parasMap.put("content", gson.fromJson(conten, JsonObject.class));
        String paras = gson.toJson(parasMap);
        System.out.println(paras);

        // 发送请求
        String content = jsonPost(InvoiceConstant.SEND_URL + interfaceUrl, paras , appId,appSecret);

        Map<String, Object> resultData = new HashMap<>();
        if (content != null && !content.isEmpty()) {
            try {
                Map<String, Object> result = gson.fromJson(content, Map.class);
                System.out.println(result);
                if ("0".equals(result.get("code"))) {
                    resultData.put("code", result.get("code"));
                    resultData.put("content", result.get("content"));
                    resultData.put("msg", result.get("msg"));
                } else {
                    resultData.put("msg", result.get("msg"));
                    resultData.put("code", result.get("code"));
                }
            } catch (Exception e) {
                resultData.put("msg", "解析响应失败");
                resultData.put("code", "1");
            }
        } else {
            resultData.put("msg", "请求无响应");
            resultData.put("code", "1");
        }

        return resultData;
    }

    /**
     * 企业查询信息
     * @return 企业信息
     */
    @Override
    public  Map<String, Object> qyxxcx() {
        // 从配置服务获取电子发票AppID
        String appId = systemConfigService.getValue(InvoiceParkingConfigConstants.INVOICE_APPID);
        // 从配置服务获取电子发票AppSecret
        String appSecret = systemConfigService.getValue(InvoiceParkingConfigConstants.INVOICE_APPSECRET);


        String interfaceUrl = "invoiceEx/zpy/electric/getMerchantInfo"; // 接口路径

        // 构建请求参数
        Map<String, Object> parasMap = new HashMap<>();
        parasMap.put("serviceId", "QYXXCX");
        parasMap.put("dlzh", InvoiceConstant.DLZH);
        parasMap.put("nsrsbh", InvoiceConstant.NSRSBH);
        parasMap.put("content", new HashMap<>());
        String paras = gson.toJson(parasMap);

        // 发送请求
        String content = jsonPost(InvoiceConstant.SEND_URL + interfaceUrl, paras,appId,appSecret);

        Map<String, Object> resultData = new HashMap<>();
        if (content != null && !content.isEmpty()) {
            try {
                Map<String, Object> result = gson.fromJson(content, Map.class);
                if ("0".equals(result.get("code"))) {
                    resultData.put("code", result.get("code"));
                    resultData.put("content", result.get("content"));
                    resultData.put("msg", result.get("msg"));
                } else {
                    resultData.put("code", result.get("code"));
                    resultData.put("msg", result.get("msg"));
                }
            } catch (Exception e) {
                resultData.put("msg", "解析响应失败");
                resultData.put("code", "1");
            }
        } else {
            resultData.put("code", "1");
            resultData.put("msg", "请求无响应");
        }

        return resultData;
    }

    /**
     * 企业抬头联想
     * @param title 企业名称
     * @return 联想结果
     */
    @Override
    public  Map<String, Object> ttlx(String title) {
        // 从配置服务获取电子发票AppID
        String appId = systemConfigService.getValue(InvoiceParkingConfigConstants.INVOICE_APPID);
        // 从配置服务获取电子发票AppSecret
        String appSecret = systemConfigService.getValue(InvoiceParkingConfigConstants.INVOICE_APPSECRET);

        String interfaceUrl = "invoiceEx/zpy/electric/invoice/enterpriseHeader"; // 接口路径

        // 构建请求参数
        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("qymc", title);

        Map<String, Object> parasMap = new HashMap<>();
        parasMap.put("serviceId", "TTLX");
        parasMap.put("content", contentMap);
        String paras = gson.toJson(parasMap);

        // 发送请求
        String content = jsonPost(InvoiceConstant.SEND_URL + interfaceUrl, paras,appId,appSecret);

        Map<String, Object> resultData = new HashMap<>();
        if (content != null && !content.isEmpty()) {
            try {
                Map<String, Object> result = gson.fromJson(content, Map.class);
                if ("0".equals(result.get("code"))) {
                    resultData.put("content", result.get("content"));
                    resultData.put("msg", result.get("msg"));
                    resultData.put("code", result.get("code"));
                } else {
                    resultData.put("msg", result.get("msg"));
                    resultData.put("code", result.get("code"));
                }
            } catch (Exception e) {
                resultData.put("msg", "解析响应失败");
                resultData.put("code", "1");
            }
        } else {
            resultData.put("msg", "请求无响应");
            resultData.put("code", "1");
        }

        return resultData;
    }

    /**
     * 上传短信验证码
     * @param code 验证码，默认666666
     * @return 操作结果
     */
    @Override
    public  Map<String, Object> scdxyzm(String code) {
        // 从配置服务获取电子发票AppID
        String appId = systemConfigService.getValue(InvoiceParkingConfigConstants.INVOICE_APPID);
        // 从配置服务获取电子发票AppSecret
        String appSecret = systemConfigService.getValue(InvoiceParkingConfigConstants.INVOICE_APPSECRET);


        String interfaceUrl = "invoiceEx/zpy/electric/auth/uploadVerificationCode"; // 接口路径

        // 构建请求参数
        Map<String, Object> contentMap = new HashMap<>();
        contentMap.put("sjhm", "186****6688");
        contentMap.put("yzm", code);

        Map<String, Object> parasMap = new HashMap<>();
        parasMap.put("serviceId", "QYXXCX");
        parasMap.put("dlzh", InvoiceConstant.DLZH);
        parasMap.put("nsrsbh", InvoiceConstant.NSRSBH);
        parasMap.put("content", contentMap);
        String paras = gson.toJson(parasMap);

        // 发送请求
        String content = jsonPost(InvoiceConstant.SEND_URL + interfaceUrl, paras,appId,appSecret);

        Map<String, Object> resultData = new HashMap<>();
        if (content != null && !content.isEmpty()) {
            try {
                Map<String, Object> result = gson.fromJson(content, Map.class);
                if ("0".equals(result.get("code"))) {
                    resultData.put("code", result.get("code"));
                    resultData.put("content", result.get("content"));
                    resultData.put("msg", result.get("msg"));
                } else {
                    resultData.put("code", result.get("code"));
                    resultData.put("msg", result.get("msg"));
                }
            } catch (Exception e) {
                resultData.put("msg", "解析响应失败");
                resultData.put("code", "1");
            }
        } else {
            resultData.put("code", "1");
            resultData.put("msg", "请求无响应");
        }

        return resultData;
    }

    /**
     * 发送JSON格式的POST请求（静态方法）
     */
    private static String jsonPost(String url, String data, String appId, String appSecret) {
        if (data == null || data.isEmpty()) {
            return "data is null";
        }
        try {

            long date = System.currentTimeMillis() / 1000;
            String accessToken = getAccessToken(appId,appSecret);
            String sign = base64Encode(md5(data + date + accessToken));

            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.setRequestProperty("Content-Length", String.valueOf(data.getBytes().length));
            connection.setRequestProperty("Cache-Control", "no-cache");
            connection.setRequestProperty("Pragma", "no-cache");
            connection.setRequestProperty("AppId", appId);
            connection.setRequestProperty("Date", String.valueOf(date));
            connection.setRequestProperty("Content-MD5", sign);

            // 发送请求数据
            OutputStream os = connection.getOutputStream();
            os.write(data.getBytes("UTF-8"));
            os.flush();
            os.close();

            // 读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), "UTF-8"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            } else {
                return "HTTP错误码: " + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "请求异常: " + e.getMessage();
        }
    }

    /**
     * 获取AccessToken（静态方法）
     */
    private static String getAccessToken(String appId , String appSecret) {
        String filePath = "./log/invoice/access_token.php";

// 确保目录存在
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        // 检查文件是否存在，不存在则创建初始文件
        if (!file.exists()) {
            try {
                FileWriter fw = new FileWriter(file);
                fw.write("<?php exit();?>{\"expireTime\":0,\"accessToken\":\"\"}");
                fw.flush();
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String fileContent = getPhpFile(filePath);

        AccessTokenData data;
        if (fileContent != null && !fileContent.isEmpty()) {
            data = gson.fromJson(fileContent, AccessTokenData.class);
        } else {
            data = new AccessTokenData();
            data.setExpireTime(0);
            data.setAccessToken("");
        }

        if (data.getExpireTime() < System.currentTimeMillis() / 1000) {
            String url = InvoiceConstant.SEND_URL2 + "?&appId=" + appId + "&appScrt=" + appSecret;
            String res = httpGet(url);

            try {
                JsonObject jsonRes = JsonParser.parseString(res).getAsJsonObject();
                String accessToken = jsonRes.getAsJsonObject("result").get("accessToken").getAsString();

                if (accessToken != null && !accessToken.isEmpty()) {
                    data.setExpireTime((int) (System.currentTimeMillis() / 1000 + 7000));
                    data.setAccessToken(accessToken);
                    setPhpFile(filePath, gson.toJson(data));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data.getAccessToken();
    }

    /**
     * 发送HTTP GET请求（静态方法）
     */
    private static String httpGet(String url) {
        try {
            URL urlObj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        connection.getInputStream(), "UTF-8"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            } else {
                return "HTTP错误码: " + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "请求异常: " + e.getMessage();
        }
    }

    /**
     * 读取PHP文件内容（静态方法）
     */
    private static String getPhpFile(String filename) {
        try {
            File file = new File(filename);
            if (file.exists() && file.isFile()) {
                BufferedReader br = new BufferedReader(new FileReader(file));
                br.readLine(); // 跳过<?php exit();?>
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString().trim();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 写入PHP文件（静态方法）
     */
    private static void setPhpFile(String filename, String content) {
        try {
            File file = new File(filename);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            FileWriter fw = new FileWriter(file);
            fw.write("<?php exit();?>" + content);
            fw.flush();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * MD5加密（静态方法）
     */
    private static String md5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] bytes = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * Base64编码（静态方法）
     */
    private static String base64Encode(String str) {
        return Base64.getEncoder().encodeToString(str.getBytes());
    }


    /**
     * 税额
     */
    private static String se(Object amountObj) {
        double amount = 0.0;

// 安全转换金额类型
        if (amountObj instanceof String) {
            amount = Double.parseDouble((String) amountObj);
        } else if (amountObj instanceof Number) {
            amount = ((Number) amountObj).doubleValue();
        }

// 计算税额（使用BigDecimal确保精度）
        BigDecimal bdAmount = BigDecimal.valueOf(amount);
        BigDecimal bdTaxRate = new BigDecimal("1.05");
        BigDecimal bdTaxAmount = bdAmount
                .subtract(bdAmount.divide(bdTaxRate, 10, RoundingMode.HALF_UP))
                .setScale(2, RoundingMode.HALF_UP);


        return bdTaxAmount.toPlainString();
    }

}
